package com.study.service.communication;

import com.alibaba.fastjson.JSON;
import com.study.constant.CommonConstant;
import com.study.vo.JwtToken;
import com.study.vo.UsernameAndPassword;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 使用 restTemplate 实现微服务通信
 */

@Slf4j
@Service
public class UseRestTemplateService {

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    public JwtToken getTokenFromAuthorityService(UsernameAndPassword usernameAndPassword){

        String requestUrl = "http://127.0.0.1:7000/" +
                "ecommerce-authority-center/authority/getToken";

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        return new RestTemplate().postForObject(
                requestUrl,
                new HttpEntity<>(JSON.toJSONString(usernameAndPassword),httpHeaders),
                JwtToken.class
        );
    }

    //从授权中心获取token 带有负载均衡
    public JwtToken getTokenFromAuthorityServiceWithloadBalancer(UsernameAndPassword usernameAndPassword){

        ServiceInstance serviceInstance = loadBalancerClient.choose(
                CommonConstant.AUTHORITY_CENTER_SERVICE_ID
        );
        log.info("nocos client 信息 [{}],[{}],[{}]",serviceInstance.getServiceId(),
                serviceInstance.getInstanceId(),JSON.toJSONString(serviceInstance.getMetadata()));

        String requestUrl = String.format("http://%s:%s/" +
                "ecommerce-authority-center/authority/getToken",
                serviceInstance.getHost(),serviceInstance.getPort()) ;

        log.info("login request url and body: [{}],[{}]",
                requestUrl,JSON.toJSONString(usernameAndPassword));

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        return new RestTemplate().postForObject(
                requestUrl,
                new HttpEntity<>(JSON.toJSONString(usernameAndPassword),httpHeaders),
                JwtToken.class
        );
    }
}
